package com.guhecloud.step.definition.runtime;


import com.guhecloud.step.definition.runtime.annotation.DomainAbility;
import com.guhecloud.step.definition.runtime.tool.InternalAopUtils;
import lombok.Getter;
import org.springframework.core.ResolvableType;

@Getter
public class DomainAbilityDef implements IRegistryAware{
    private BaseDomainAbility domainAbilityBean;
    private String domain;
    private String name;
    private Class<? extends BaseDomainAbility> domainAbilityClass;
    private Class<? extends IDomainExtension> extClazz;
    @Override
    public void registerBean(Object bean) {
        DomainAbility domainAbility = InternalAopUtils.getAnnotation(bean, DomainAbility.class);
        this.domain = domainAbility.domain();
        this.name = domainAbility.name();
        if (!(bean instanceof BaseDomainAbility)) {
            throw new RuntimeException("必须是BaseDomainAbility的子类");
        }

        this.domainAbilityBean = (BaseDomainAbility) bean;
        this.domainAbilityClass = (Class<? extends BaseDomainAbility>) InternalAopUtils.getTarget(bean).getClass();

        this.resolveExtClazz();

        InternalIndexer.index(this);
    }


    private void resolveExtClazz() {
        ResolvableType baseDomainAbilityType = ResolvableType.forClass(this.domainAbilityClass).getSuperType();
        // 5层继承
        for (int i = 0; i < 5; i++) {
            for (ResolvableType resolvableType : baseDomainAbilityType.getGenerics()) {
                if (IDomainExtension.class.isAssignableFrom(resolvableType.resolve())) {
                    this.extClazz = (Class<? extends IDomainExtension>) resolvableType.resolve();
                    return;
                }

            }
            baseDomainAbilityType = baseDomainAbilityType.getSuperType();
        }
    }
}
